<template>
  <div class="index-box">
    <div class="content-head">
      <a-row align="middle">
        <a-col span="14">
          <a-button type="primary" icon="plus" @click="() => { roleSetModal = true;roleSetModalTitle = '添加角色'; }">新增角色</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="content-body">
      <a-table :columns="columns" rowKey="id" :pagination="pagination" :dataSource="dataSource" :loading="loading" @change="tableChange">
        <template slot="operation" slot-scope="text,record">
          <a-dropdown>
            <a class="ant-dropdown-link" href="javascript:void(0);">操作 <a-icon type="down" /></a>
            <a-menu slot="overlay" @click="operation($event,record)">
              <a-menu-item key="1">编辑</a-menu-item>
              <a-menu-item key="2">删除</a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <!-- 添加or编辑角色弹窗 -->
    <a-modal :title="roleSetModalTitle" v-model="roleSetModal" :confirmLoading="roleSetModalConfirmLoading" :afterClose="afterCloseUnitModal" @ok="handleSubmit">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="姓名" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-input placeholder="请输入姓名" v-decorator="['name',{rules:[{required:true,message:'姓名不可为空'}],initialValue:''}]"></a-input>
        </a-form-item>
        <a-form-item label="手机号" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-input placeholder="请输入手机号" v-decorator="['mobile',{rules:[{required:true,message:'姓名不可为空'},{pattern:/^1[3456789]\d{9}$/,message:'请输入正确的手机号'}],initialValue:''}]"></a-input>
        </a-form-item>
        <a-form-item label="密码" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}" :extra="roleSetModalTitle === '编辑角色' ? '如不修改请留空' : ''">
          <a-input type="password" placeholder="请输入密码" v-decorator="['password',{rules:[typeof form.getFieldValue('id') === 'undefined' || form.getFieldValue('id') == 0 ? {required:true,message:'密码不可为空'} : {}],initialValue:''}]"></a-input>
        </a-form-item>
        <a-form-item label="所属群组" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-select :options="groupList" placeholder="请选择所属群组" v-decorator="['wy_auth_id',{rules:[{required:true,message:'请选择所属群组'}],initialValue:undefined}]" />
        </a-form-item>
        <a-form-item label="关联小区" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}" extra="选择当前角色可管理小区">
          <a-select mode="multiple" optionFilterProp="children" :options="communityList" placeholder="请选择关联小区" v-decorator="['cm_message_id',{rules:[{required:true,message:'请选择角色可管理小区'}],initailValue:[]}]" />
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input type="hidden" v-decorator="['id',{initialValue:0}]"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { mapGetters } from 'vuex'
  export default {
    name: 'purview_role',
    data() {
      return {
        description:'角色关联群组,授权管理小区',
        form:this.$form.createForm(this),
        token:this.$ls.get(ACCESS_TOKEN),
        roleSetModalTitle:'添加员工',
        roleSetModal:false, // 添加or编辑员工弹窗
        roleSetModalConfirmLoading:false, // 添加or编辑员工确定按钮loading状态
        columns:[
          {
            title:'编号',
            dataIndex:'id'
          },
          {
            title:'姓名',
            dataIndex:'name'
          },
          {
            title:'手机号',
            dataIndex:'mobile'
          },
          {
            title:'所属群组',
            dataIndex:'wy_auth_name'
          },
          {
            title:'操作',
            dataIndex:'operation',
            scopedSlots:{customRender:'operation'}
          }
        ],
        groupList:[], // 群组列表
        communityList:[], // 小区列表
        pagination:{}, // 表格分页
        dataSource:[], // 表格数据
        loading:false,
      }
    },
    mounted() {
      this.roleList();
      this.getAllGroupAndCommunity();
    },
    methods:{
      ...mapGetters(['userInfo']),
      // 角色列表
      roleList(page = 1) {
        this.loading = true;
        this.axios({
          method:'post',
          url:'/purview/roleList',
          data:{token:this.token,page}
        }).then(res => {
          Object.assign(res.data.info,{ hideOnSinglePage:true });
          this.pagination = res.data.info;
          this.dataSource = res.data.data;
          this.loading = false;
        }).catch(err => {
          this.loading = false;
          this.$message.error('服务器发生错误...',2);
        });
      },
      // 表格分页及其他事件
      tableChange(pagination, filters, sorter) {
        this.roleList(pagination.current);
      },
      // 下拉菜单操作按钮
      operation({ key },info) {
        const _this = this;
        // 编辑
        if(key === '1'){
          this.roleSetModal = true;
          this.roleSetModalTitle = '编辑角色';
          this.$nextTick(() => {
            _this.form.setFieldsValue({id:info.id,name:info.name,mobile:info.mobile,wy_auth_id:info.wy_auth_id,cm_message_id:info.cm_message_id.split(',').map(item => Number(item))});
          })
        }
        if(key === '2'){
          this.$confirm({
            title: `确定要删除\"${info.name}\"角色？`,
            content:'删除后将不可恢复',
            onOk() {
              return new Promise((resolve, reject) => {
                _this.axios({
                  method:'post',
                  url:'/purview/delRole',
                  data:{token:_this.token,id:info.id},
                }).then(res => {
                  if(res.code === 0){
                    _this.$message.success(res.msg,2);
                    _this.roleList();
                    resolve();
                  }else reject(res.msg);
                }).catch(err => {
                  _this.$message.error('服务器发生错误...',2);
                })
              }).catch((msg) => _this.$message.error(msg,2));
            },
            onCancel() {},
          });
        }
      },
      // 确定添加or修改角色
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2);
            }
          }
          Object.assign(values,{token:this.token})
          this.roleSetModalConfirmLoading = true;
          this.axios({
            method:'post',
            url:'/purview/operationRole',
            data:values,
          }).then(res => {
            if(res.code === 0){
              this.$message.success(res.msg,2);
              this.roleSetModal = false;
              this.roleSetModalConfirmLoading = false;
              this.roleList();
            }else this.$message.error('服务器发生错误...',2);
          }).catch((err) => {
            this.$message.error('服务器发生错误...',2);
          })
        })
      },
      // 弹窗完全关闭
      afterCloseUnitModal() {
        this.form.resetFields();
        this.roleSetModalConfirmLoading = false;
      },
      // 获取所有群组和小区
      getAllGroupAndCommunity() {
        this.axios({
          method:'post',
          url:'/purview/getAllGroupAndCommunity',
          data:{token:this.token}
        }).then(res => {
          this.groupList = res.data.group;
          this.communityList = res.data.community;
        }).catch(err => this.$message.error('服务器发生错误... 群组和小区获取失败',2));
      }
    }
  }
</script>

<style lang="less" scoped>
  .index-box{
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
    .content-body{
      padding-top:20px;
    }
  }
</style>